<?php
namespace Application\Api\Controller;

class QrLogin extends Base
{

    private $time = MINUTE_5;

    /*
        /Api/QrLogin/getName
    */
    public function getNameAction()
    {
        $name = uniqid();
        $this->get(CACHE_QRLOGIN)->setData($name, $this->time, '1');
        $data = [
            'name' => $name,
            'report_url' => getDomain() . '/Api/QrLogin/report'
        ];
        $this->sendSuccess($data);
    }

    /*
        /Api/QrLogin/query
    */
    public function queryAction()
    {
        $data = $this->getRequestData();
        if(notSetOrEmpty($data, 'name')){
            $this->sendFail('PARAMETER_ERROR');
            return false;
        }
        $name = $data['name'];
        $value = $this->get(CACHE_QRLOGIN)->getData($name);
        $action = '';
        /*键不存在*/
        if(!$value || $value == 'cancel'){
            $action = 'refresh';
        }
        else if($value == '1'){
            $action = 'query';
        }
        /*只是扫码，还未确认*/
        else if($value == 'success'){
            $action = 'scan';
        }
        /*已经确认了*/
        else{
            $action = 'write';
        }
        if(!$value){
            $value = '';
        }
        $data = [
            'action' => $action,
            'name' => $name,
            'value' => $value
        ];
        $this->sendSuccess($data);
    }

    /*
        /Api/QrLogin/report
    */
    public function reportAction()
    {
        $data = $this->getRequestData();
        if(notSetOrEmpty($data, 'name') || notSetOrEmpty($data, 'app_device') || notSetOrEmpty($data, 'device') || notSetOrEmpty($data, 'token')){
            $this->sendFail('PARAMETER_ERROR');
            return false;
        }
        $name = $data['name'];
        $appDevice = $data['app_device'];
        $device = $data['device'];
        $token = $data['token'];
        $serviceUser = $this->get(SERVICE_USER);
        $userId = $serviceUser->checkToken($data, $appDevice);
        if($userId){
            /*
                需要根据设备和用户id重新生成token，不能用APP的token
            */
            $token = $serviceUser->setToken($device, $userId);
        }
        $this->get(CACHE_QRLOGIN)->setData($name, $this->time, $token);
        $this->sendSuccess();
    }

}